package cn.gogoyc.user.service.impl;

import cn.gogoyc.org.basic.exception.BusinessException;
import cn.gogoyc.org.basic.jwt.JwtUtils;
import cn.gogoyc.org.basic.jwt.LoginData;
import cn.gogoyc.org.basic.jwt.RsaUtils;
import cn.gogoyc.org.basic.servie.impl.BaseServiceImpl;
import cn.gogoyc.org.basic.util.AjaxResult;
import cn.gogoyc.org.basic.util.HttpUtil;
import cn.gogoyc.org.basic.util.Md5Utils;
import cn.gogoyc.org.basic.util.StrUtils;
import cn.gogoyc.system.domain.Menu;
import cn.gogoyc.user.constant.WxConstants;
import cn.gogoyc.user.domain.Logininfo;
import cn.gogoyc.user.domain.User;
import cn.gogoyc.user.domain.Wxuser;
import cn.gogoyc.user.dto.LoginDto;
import cn.gogoyc.user.mapper.LogininfoMapper;
import cn.gogoyc.user.mapper.UserMapper;
import cn.gogoyc.user.mapper.WxuserMapper;
import cn.gogoyc.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统信息业务实现类
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        //非空判断
        if (StringUtils.isEmpty(loginDto.getAccount()) || StringUtils.isEmpty(loginDto.getCheckPass())) {
            throw new BusinessException("请输入正确信息...");
        }

        //根据所传的数据查询,判断是否有该对象
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null) {
            throw new BusinessException("账号错误...");
        }

        //走到这里说明有对应数据,将该对象的密码进行加盐加密处理。
        String inputMd5Pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        /*String inputMd5Pwd = "RwDBZolEP0c2fUimoAcf4E8KJ2wtWRtl";*/
        //拿加工后的密码和查询到的对象密码进行比较,如果不正确则提醒密码错误
        if (!inputMd5Pwd.equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误...");
        }

        //判断该对象的状态
        if (!logininfo.getDisable()) {
            throw new BusinessException("该账户已禁用,请联系管理员处理...");
        }
        //将登录用户的信息放入jwt加密添加进map中返回给前端
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        //这里返回给前端的是一个logininfo对象信息和一个加密的jwt私钥,这个私钥方便下次登录的时候判断
        return map;
    }

    /**
     * 微信登录
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {
        //配置请求
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);

        //后台发送请求,获取返回参数
        String jsonStr = HttpUtil.httpGet(url);
        //将json字符串转为json对象
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        //获取对象中指定的登录token和openId 方便传回给前端发第三次请求
        String access_token = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //根据Openid去查询该用户是否注册过
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        //注册过则进入if
        if (wxuser != null) {
            //根据wxID去查询对应的用户表信息
            User user = userMapper.loadById(wxuser.getUserId());
            if (user != null) {
                //根据该wx的用户id查询到用户信息,再通过用户信息查询到系统信息
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                //返回给前端一个map集合
                return AjaxResult.me().setObj(map);
            }
        }
        //返回是第一次登录,数据库中没有扫码用户的信息,则将登录token和openId返回给前端。
        return AjaxResult.me().setSuccess(false).setObj("?access_token=" + access_token + "&openid=" + openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.校验-空值
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("信息不能为空,请认真填写");
        }
        //2.校验-手机验证码：是否过期，是否正确
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if (obj == null) {
            throw new BusinessException("验证码已过期,请重新获取填写");
        }
        if (phone.equals(obj.toString().split(":")[0])) {
            throw new BusinessException("手机验证码错误!!!");
        }
        //3.准备第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //4.使用HttpUtil发送微信绑定请求 - 获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换WxUser对象
        Wxuser wxuser = jsonStr2WxUser(jsonStr);
        //6.创建User对象和Logininfo对象【phone】 - 难度
        //微信注册的用户是第一次,但可能用手机或邮箱注册过,判断user表中是否有相同的数据
        User user = userMapper.loadByPhone(phone);
        if (user == null) {
            //新对象
            user = phone2User(phone);
            //复制给logininfo同步
            Logininfo logininfo = user2Logininfo(user);
            //先添加,user关联logininfo的话需要他的自增ID
            logininfoMapper.save(logininfo);

            //根据添加好的logininfo自增ID 关联上
            user.setLogininfoId(logininfo.getId());
            //关联好后入库
            userMapper.save(user);

        }
        //如果之前用手机号或邮箱注册过,则和user表关联上
        wxuser.setUserId(user.getId());
        //微信对象入库
        wxuserMapper.save(wxuser);
        //7.添加数据库：Logininfo对象 - User对象 - WxUser对象
        //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        //查询该用户的信息并用jwt加密后放入map中返回给前端处理
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setObj(resultMap);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    //根据唯一标识手机创建新对象并入库
    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String randomPwd = StrUtils.getComplexRandomString(12);
        String md5Pwd = Md5Utils.encrypByMd5(salt + randomPwd);
        user.setPassword(md5Pwd);
        user.setSalt(salt);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2WxUser(String jsonStr) {
        /*
        * {
            "openid":"OPENID",
            "nickname":"NICKNAME",
            "sex":1,
            "province":"PROVINCE",
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl": "https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
            "privilege":[
            "PRIVILEGE1",
            "PRIVILEGE2"
            ],
            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
          }
           **/
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }

    public Map<String, Object> loginSuccessJwtHandler(Logininfo loginInfo){
        Map<String, Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        //localStorage中不展示盐值和密码变为null
        loginInfo.setPassword(null);
        loginInfo.setSalt(null);
        //添加进map返回给前端
        map.put("logininfo",loginInfo);
        //jwt载荷数据
        loginData.setLogininfo(loginInfo);

        //判断是用户还是管理员
        if (loginInfo.getType() == 0){
            //查询当前对象拥有的权限
            List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(loginInfo.getId());
            //添加进map返回给前端
            map.put("permissions",permissions);
            //jwt载荷数据
            loginData.setPermissions(permissions);

            //查询当前对象拥有的菜单
            List<Menu> menus = logininfoMapper.findMenusByLogininfoId(loginInfo.getId());
            //添加进map返回给前端
            map.put("menus",menus);
            //jwt载荷数据
            loginData.setMenus(menus);
        }

        try {
            //创建私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //将载荷数据放入私钥中,并加密设置有效时间
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300000);
            //将加密的私钥添加进map返回给前端
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
